package com.google.ideas.MobileMeme;

import com.google.ideas.MobileMeme.meme.BaseImage;
import com.google.ideas.MobileMeme.meme.ImageStore;
import com.google.ideas.MobileMeme.meme.ImageStoreAdapter;

import android.app.Activity;
import android.app.LoaderManager;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

public class ViewTemplates extends Activity implements LoaderManager.LoaderCallbacks<List<BaseImage>>{
  private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
  private static final String VIEW_TEMPLATE_ACTIVITY = "view_template_activity";
  public static final int TAKE_A_PICTURE = 1;
  public static final String ACTION_CODE 
    = "com.google.ideas.MobileMeme.ViewTemplates.ACTION_CODE";
	
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_templates);

    Button take_picture = (Button) findViewById(R.id.takePhotoBtn);
    // disable the 'take a picture' button if we don't have a camera
    if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
      take_picture.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View v) {
          takeAPicture();
        }
      });
    } else {
      take_picture.setEnabled(false);
    }

    store_ = new ImageStore(this);
    adapter_ = new ImageStoreAdapter(store_, this);
    getLoaderManager().initLoader(LOADER_IMAGESTORE, null, this);
    ListView images = (ListView) findViewById(R.id.pictureList);
    images.setAdapter(adapter_);

    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
      if (bundle.containsKey(ACTION_CODE)) {
        int action_code = bundle.getInt(ACTION_CODE, -1); 
        switch(action_code) {
          case TAKE_A_PICTURE:
            takeAPicture();
            return;
          default:
            Log.d(
                VIEW_TEMPLATE_ACTIVITY, 
                "Got an invalid action code for intent: " + action_code);
        }
      }
    }
  }
  private File getPhotoTempFile() {
    final File path = new File(
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
          + File.separator + getPackageName());
    if (!path.exists()) {
      Log.i(VIEW_TEMPLATE_ACTIVITY, "getPhotoTempFile: " + path + " does not exist.  Creating");
      
      boolean res = path.mkdirs();
      if (!res) {
        Log.e(VIEW_TEMPLATE_ACTIVITY, "getPhotoTempFile: could not create!!");
      }
    }
    File retval = new File(path, "photo.tmp");
    Log.i(VIEW_TEMPLATE_ACTIVITY, "getPhotoTempFile: returning " + retval);
    return retval;
  }    
  
    /* Start an Intent to take a picture, and bounce it back to use in onActivityResult.
     */
    private void takeAPicture() {
        // Note: we only get a preview in the "data" part of the Bundle.
        // If I give a filename, I get the real image in that file.

        // Create Intent to take a picture and return control to the calling
        // application
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);        
        // Tell it where to save the photo.
        intent.putExtra(MediaStore.EXTRA_OUTPUT, 
                        Uri.fromFile(getPhotoTempFile()));
        // start the image capture Intent
        startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
    }

    /* Process results from any activities we've run.  Namely, the camera app. 
	 * @see android.support.v4.app.FragmentActivity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
	  if (requestCode ==  CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
	    if (resultCode == RESULT_OK) {
	      try {
	        Bitmap imagedata = Media.getBitmap(getContentResolver(), Uri.fromFile(getPhotoTempFile()));
	        // we don't need to calculate the hash here, the ImageStore will do that for us.
	        BaseImage image = new BaseImage("IMG_" + imagedata.hashCode(), imagedata, null);
	        String hash = store_.saveImage(store_.getWritableDatabase(), image);
	        image.setHash(hash);
	        imagedata.setDensity(DisplayMetrics.DENSITY_DEFAULT);
	        int width = imagedata.getWidth();
	        int height = imagedata.getHeight();
	        Log.i(VIEW_TEMPLATE_ACTIVITY, "Saved a ("+width+"x"+height+") image: " + image);
	        getLoaderManager().restartLoader(LOADER_IMAGESTORE, null, this);
	        adapter_.notifyDataSetChanged();
	        getPhotoTempFile().delete();
	      } catch (FileNotFoundException e) {
	        e.printStackTrace();
	      } catch (IOException e) {
	        e.printStackTrace();
	      }
	    } else if (resultCode != RESULT_CANCELED) {
	      Log.e(VIEW_TEMPLATE_ACTIVITY, "Got error " + resultCode + " when trying to take a picture.");
	    }
	  } else {
	    super.onActivityResult(requestCode, resultCode, intent);
	  }
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_view_templates, menu);
        return true;
    }
    private ImageStore store_;
    private ImageStoreAdapter adapter_;
    private final int LOADER_IMAGESTORE = 100;

	@Override
	public Loader<List<BaseImage>> onCreateLoader(int id, Bundle args) {
		if (id == LOADER_IMAGESTORE) {
			Log.d(VIEW_TEMPLATE_ACTIVITY, "onCreateLoader() returning getLoader()");
			return adapter_.getLoader();
		}
		return null;
	}

	@Override
	public void onLoadFinished(Loader<List<BaseImage>> loader,
			List<BaseImage> results) {
		Log.d(VIEW_TEMPLATE_ACTIVITY, "onLoadFinished: got " + results.size() + " items");
		adapter_.setImages(results);		
	}

	@Override
	public void onLoaderReset(Loader<List<BaseImage>> arg0) {
		Log.d(VIEW_TEMPLATE_ACTIVITY, "onLoaderReset()");
		adapter_.setImages(null);
	}
}
